package com.southminority.ethnic.controller.admin.heritage;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.HeritageResearchLink;
import com.southminority.ethnic.service.heritage.HeritageResearchLinkService;
import com.southminority.ethnic.controller.heritage.vo.HeritageResearchLinkVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 非遗研究成果管理后台控制器
 * 提供管理员的完整CRUD操作
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "07 - 非物质文化遗产管理API", description = "【后台】非物质文化遗产、传承人等模块的增删改查接口")
@RestController
@RequestMapping("/admin/heritage/research-links")
@CrossOrigin
public class HeritageResearchLinkAdminController {

    private final HeritageResearchLinkService researchLinkService;

    public HeritageResearchLinkAdminController(HeritageResearchLinkService researchLinkService) {
        this.researchLinkService = researchLinkService;
    }

    /**
     * 分页查询研究成果关联列表
     */
    @GetMapping("/page")
    @Operation(summary = "【研究成果】分页和条件查询", description = "后台管理使用的研究成果关联列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<PageResult<HeritageResearchLinkVO>> getResearchLinkPageForAdmin(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关联的非遗项目ID", example = "1") @RequestParam(required = false) Long heritageId,
            @Parameter(description = "搜索关键词，模糊匹配标题和简介", example = "文化") @RequestParam(required = false) String keyword,
            @Parameter(description = "关联类型", example = "paper", schema = @Schema(allowableValues = {"link", "report", "paper", "project", "progress", "patent"})) @RequestParam(required = false) String type,
            @Parameter(description = "状态", example = "1", schema = @Schema(description = "1-正常, 0-禁用, -1-已删除", type = "integer", allowableValues = {"1", "0", "-1"})) @RequestParam(required = false) Integer status) {
        try {
            PageResult<HeritageResearchLinkVO> pageResult = researchLinkService.getResearchLinkPageForAdmin(
                page, size, heritageId, keyword, type, status);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("分页查询研究成果关联失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取研究成果详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "【研究成果】获取单条关联详情", description = "根据关联ID获取其详细信息。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "关联记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageResearchLinkVO> getResearchLinkDetail(
            @Parameter(description = "研究成果关联记录的唯一ID", example = "1", required = true) @PathVariable Long id) {
        try {
            HeritageResearchLinkVO researchLink = researchLinkService.getResearchLinkDetail(id);
            return R.ok(researchLink);
        } catch (Exception e) {
            log.error("获取研究成果详情失败, ID: {}", id, e);
            return R.fail("获取详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建研究成果关联
     */
    @PostMapping
    @Operation(summary = "【研究成果】新增一条关联记录", description = "创建一个新的非遗项目与研究成果的关联。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功，返回创建后的关联信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageResearchLinkVO> createResearchLink(
            @RequestBody(description = "研究成果关联信息的JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = HeritageResearchLink.class)))
            @org.springframework.web.bind.annotation.RequestBody HeritageResearchLink researchLink) {
        try {
            HeritageResearchLinkVO result = researchLinkService.createResearchLink(researchLink);
            log.info("成功创建研究成果关联，ID: {}", result.getId());
            return R.ok(result);
        } catch (Exception e) {
            log.error("创建研究成果关联失败", e);
            return R.fail("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新研究成果关联
     */
    @PutMapping("/{id}")
    @Operation(summary = "【研究成果】根据ID更新关联信息", description = "提供关联ID和更新后的信息，对现有记录进行修改。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功，返回更新后的关联信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "关联记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<HeritageResearchLinkVO> updateResearchLink(
            @Parameter(description = "要更新的关联记录ID", example = "1", required = true) @PathVariable Long id,
            @RequestBody(description = "包含更新字段的关联信息JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = HeritageResearchLink.class)))
            @org.springframework.web.bind.annotation.RequestBody HeritageResearchLink researchLink) {
        try {
            HeritageResearchLinkVO result = researchLinkService.updateResearchLink(id, researchLink);
            log.info("成功更新研究成果关联，ID: {}", id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新研究成果关联失败, ID: {}", id, e);
            return R.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除研究成果关联
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "【研究成果】根据ID逻辑删除关联", description = "将指定ID的关联记录状态设置为-1，并非物理删除。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "关联记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteResearchLink(
            @Parameter(description = "要删除的关联记录ID", example = "1", required = true) @PathVariable Long id) {
        try {
            Boolean result = researchLinkService.deleteResearchLink(id);
            log.info("成功删除研究成果关联，ID: {}", id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("删除研究成果关联失败, ID: {}", id, e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除研究成果关联
     */
    @DeleteMapping("/batch")
    @Operation(summary = "【研究成果】批量逻辑删除关联", description = "传入一个ID列表，批量将对应的关联记录状态设置为-1。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "ID列表为空"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> batchDeleteResearchLink(
            @RequestBody(description = "包含多个关联记录ID的数组", required = true,
                    content = @Content(schema = @Schema(type = "array", implementation = Long.class))) List<Long> ids) {
        try {
            Boolean result = researchLinkService.batchDeleteResearchLink(ids);
            log.info("成功批量删除研究成果关联，数量: {}", ids.size());
            return R.ok(result);
        } catch (Exception e) {
            log.error("批量删除研究成果关联失败, IDs: {}", ids, e);
            return R.fail("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 更新研究成果状态
     */
    @PutMapping("/{id}/status")
    @Operation(summary = "【研究成果】更新关联状态", description = "更新单个关联记录的状态，如启用（1）和禁用（0）。")
    @Parameters({
            @Parameter(name = "id", description = "关联记录ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(description = "1-启用, 0-禁用", type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "关联记录不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateResearchLinkStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            Boolean result = researchLinkService.updateResearchLinkStatus(id, status);
            log.info("成功更新研究成果状态，ID: {}, status: {}", id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("更新研究成果状态失败, ID: {}, status: {}", id, status, e);
            return R.fail("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 根据非遗项目ID获取相关研究成果（管理端查看）
     */
    @GetMapping("/by-heritage/{heritageId}")
    @Operation(summary = "【研究成果】获取指定非遗项目下的所有关联", description = "根据非遗项目ID，查询其关联的所有研究成果列表（不分页），主要用于管理界面的快速查看。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<List<HeritageResearchLinkVO>> getResearchLinksByHeritageId(
            @Parameter(description = "非遗项目的ID", example = "1", required = true) @PathVariable Long heritageId) {
        try {
            List<HeritageResearchLinkVO> researchLinks = researchLinkService.getResearchLinksByHeritageId(heritageId);
            return R.ok(researchLinks);
        } catch (Exception e) {
            log.error("获取非遗项目相关研究成果失败, 非遗ID: {}", heritageId, e);
            return R.fail("获取相关研究成果失败: " + e.getMessage());
        }
    }
} 